﻿using System;
using System.Web.UI.WebControls;
using br.com.SistemaChamados.Constants;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Enum;
using br.com.SistemaChamados.Model;
using System.Web.Security;
using br.com.SistemaChamados.Controller.Common;
using br.com.SistemaChamados.Util;

public partial class Pages_CallSubCategoryUpdate : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        ViewStateUserKey = Session.SessionID;
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        br.com.SistemaChamados.Model.Common.User loggedUser = new br.com.SistemaChamados.Model.Common.User();
        UserController userController = new UserController();
        if (Session[UserConstants.SESSION_USER_LOGGED_IN] != null)
        {
            loggedUser.Id = Convert.ToInt32(Session[UserConstants.SESSION_USER_LOGGED_IN]);
            loggedUser = userController.GetUser(loggedUser);
            this.MasterPageFile = MasterPageDefiner.defineMasterPageByAccessRole(loggedUser.Profile);
            ((Label)Master.FindControl("lblUser")).Text = loggedUser.Name;
            this.Title = "SysCall - Sistema de chamados [logado como " + loggedUser.Name + "]";
        }
        else
        {
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (User.IsInRole("ADMIN"))
        {
            if (!IsPostBack)
            {
                FillDdl();
                FillData();
            }
        }
        else
        {
            FormsAuthentication.SignOut();
            Response.Clear();
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    private void FillData()
    {
        string id = Session[CallSubCategoryConstants.SESSION_SUBCALLCATEGORY_ID].ToString();
        CallSubCategory callSubCategory = new CallSubCategory();
        callSubCategory.Id = Convert.ToInt32(id);
        CallSubCategoryController callSubCategoryController = new CallSubCategoryController();
        CallSubCategory newCallSubCategory = new CallSubCategory();
        try
        {
            newCallSubCategory = callSubCategoryController.GetCallSubCategory(callSubCategory);
            if (newCallSubCategory != null)
            {
                txbSubCategory.Text = newCallSubCategory.Description.Trim();
            }
            ListItem list = ddlCategory.Items.FindByValue(Convert.ToString(newCallSubCategory.CallCategory.Id));

            for (int i = 0; i < ddlCategory.Items.Count; i++)
            {
                ddlCategory.Items[i].Selected = false;
            }
            if (list != null)
            {
                list.Selected = true;
            }
            else
            {
                ddlCategory.Items[0].Selected = true;
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro no carregamento das subcategorias: <br>" + ex.Message +
                               ".');</script>");
        }
    }

    private void FillDdl()
    {
        CallCategoryController callCategoryController = new CallCategoryController();
        ddlCategory.DataSource = callCategoryController.GetCallCategories();
        ddlCategory.DataTextField = "Description";
        ddlCategory.DataValueField = "Id";
        ddlCategory.DataBind();
        ddlCategory.Items.Insert(0, "Selecione");
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            if (ddlCategory.SelectedIndex != 0)
            {
                CallSubCategory callSubCategory = new CallSubCategory();
                CallSubCategoryController callSubCategoryController = new CallSubCategoryController();
                CallCategory callCategory = new CallCategory();
                callCategory.Id = Convert.ToInt32(ddlCategory.SelectedValue);
                string id = Session[CallSubCategoryConstants.SESSION_SUBCALLCATEGORY_ID].ToString();

                callSubCategory.Id = Convert.ToInt32(id);
                callSubCategory.Description = Convert.ToString(txbSubCategory.Text);
                callSubCategory.CallCategory = callCategory;

                if (callSubCategoryController.UpdateCallSubCategory(callSubCategory) == EnumGenericState.GENERIC_STATE_SUCCESS)
                {
                    Response.Write(@"<script language='javascript'>alert('Subcategoria alterada com sucesso!');</script>");
                    Response.Redirect("CallSubCategoryMain.aspx");
                }
                else
                {
                    Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante a atualização, por favor tente novamente!');</script>");
                }
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Selecione uma categoria.');</script>");
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro ao atualizar: <br>" + ex.Message + ".');</script>");

            throw ex;
        }
        finally
        {
            Session.Remove(CallSubCategoryConstants.SESSION_SUBCALLCATEGORY_ID);
        }
    }
}